package demo

import (
	"log"
	"os"

	"gitee.com/general252/ebml-go/core"
	"gitee.com/general252/ebml-go/core/codecs"
	"gitee.com/general252/ebml-go/mkv"
	"gitee.com/general252/ebml-go/mkvcore"
	"gitee.com/general252/ebml-go/webm"
	"github.com/bluenviron/mediacommon/pkg/codecs/h265"
)

func HevcDemo() {
	var inFilename = "480x272.hevc"
	var outFilename = "outHevc.mkv"

	w, err := os.OpenFile(outFilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		log.Println(err)
		return
	} else {
		defer w.Close()
	}

	ws, err := webm.NewSimpleBlockWriter(w,
		[]*webm.TrackEntry{
			{
				Name:            "Video",
				TrackNumber:     1,
				TrackUID:        12345,
				CodecID:         core.VideoCodecMPEGHISOHEVC,
				TrackType:       1,
				DefaultDuration: 40000000,
				Video: &webm.Video{
					PixelWidth:  704,
					PixelHeight: 576,
				},
			},
		},
		mkvcore.WithSeekHead(true),
		mkvcore.WithEBMLHeader(mkv.DefaultEBMLHeader),
		mkvcore.WithSegmentInfo(mkv.DefaultSegmentInfo),
		mkvcore.WithMaxKeyframeInterval(1, 900*0x6FFF),
	)
	if err != nil {
		log.Println(err)
		return
	} else {
		defer ws[0].Close()
	}

	videoStream := ws[0]

	fp, err := os.Open(inFilename)
	if err != nil {
		log.Println(err)
		return
	}

	var (
		timestamp int64
		startCode = []byte{0x0, 0x0, 0x0, 0x01}
		ss        []h265.NALUType
	)

	codecs.EmitNALUH265Reader(fp, codecs.NALUFormatAnnexB, codecs.NALUFormatNo, func(t h265.NALUType, bytes []byte) {
		ss = append(ss, t)
		switch t {
		case h265.NALUType_TRAIL_R:
			_, _ = videoStream.Write(false, timestamp, append(startCode, bytes...))
			timestamp += 40
		case h265.NALUType_VPS_NUT:
			_, _ = videoStream.Write(false, timestamp, append(startCode, bytes...))
			timestamp += 40
		case h265.NALUType_SPS_NUT:
			_, _ = videoStream.Write(false, timestamp, append(startCode, bytes...))
			timestamp += 40
		case h265.NALUType_PPS_NUT:
			_, _ = videoStream.Write(false, timestamp, append(startCode, bytes...))
			timestamp += 40
		case h265.NALUType_IDR_W_RADL:
			_, _ = videoStream.Write(true, timestamp, append(startCode, bytes...))
			timestamp += 40
		}
	})

	log.Println(ss)

}
